package com.shiva.oms;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;

import com.shiva.oms.logview.domain.LogData;
import com.shiva.oms.logview.util.SshTransferHelper;
import com.sshtools.j2ssh.SshClient;
import com.sshtools.j2ssh.authentication.AuthenticationProtocolState;
import com.sshtools.j2ssh.authentication.PasswordAuthenticationClient;
import com.sshtools.j2ssh.sftp.SftpFile;

/**
 * 
 * 
 * 
 * <pre>
 * HISTORY
 * ****************************************************************************
 *  ID    DATE            PERSON            REASON
 *  1     2018年4月9日         LA.01367604           Create
 * ****************************************************************************
 * </pre>
 * 
 * @author LA.01367604
 * @version 1.0
 */
public class Exemple2 {

    private final String IP = "10.202.38.213";// 10.202.41.26 10.202.38.213 
    private final String USERNAME = "appdeploy";
    private final String PASSWORD = "sf123456";
    private final String PATH = "/app/jetty/server/SHIVA_OMS_CNSZ22_JETTY_APP_REC_ORDER_01/logs/";// /home/appdeploy/appointment/logs/ /app/jetty/server/SHIVA_OMS_CNSZ22_JETTY_APP_REC_ORDER_01/logs
    private Connection conn = null;
    private int lastModifyTime = 0;
    
    public boolean copyLogFile(String fileName, long updateTime){
        try {
            // connect linux host
            this.conn = new Connection(this.IP);
            this.conn.connect();
            boolean isAuthenticated = this.conn.authenticateWithPassword(this.USERNAME, this.PASSWORD);
            System.out.println("Connecting to "+ IP + "@" + USERNAME + (isAuthenticated?" successful":" failed"));//logger.info
            if (isAuthenticated) {
                long startTime = System.currentTimeMillis(); // 获取开始时间
                // scp 复制文件到本地
                File buffFile = new File("E:\\tempFromLinux.tmp");
                SCPClient scpClient = conn.createSCPClient();
                OutputStream os = new FileOutputStream(buffFile);
                scpClient.get(this.PATH + "novatar_20180411.0.log", os);
                InputStream is = new FileInputStream(buffFile);
                BufferedReader br = new BufferedReader(new InputStreamReader(is));

//                 Session session = this.conn.openSession();
//                 session.execCommand("cat "+this.PATH+"novatar_20180411.0.log");
//                 // 远程执行命令
//                 InputStream is = new StreamGobbler(session.getStdout());
//                 BufferedReader br = new BufferedReader(new InputStreamReader(is));

                // long endTime = System.currentTimeMillis(); // 获取结束时间
                while (true) {
                    String line = br.readLine();
                    if (line == null) {
                        // System.out.println("远程服务器返回信息:空");
                        break;
                    }

                    System.out.println(line);
                }

                // SFTPv3Client sftpClient = new SFTPv3Client(this.conn);
                // // this.lastModifyTime = sftpClient.lstat(this.PATH +
                // fileName).mtime;
                //
                // SFTPv3FileHandle handle = sftpClient.openFileRO(this.PATH +
                // fileName);
                // byte[] dst = new byte[101];
                // sftpClient.read(handle, 0L, dst, 0, 100);
                
                // session远程执行命令
//                Session session = this.conn.openSession();   
//                session.execCommand("vim /home/appdeploy/appointment/logs/error.log");   //远程执行命令   
//                InputStream stdout = new StreamGobbler((session.getStdout());   
//                BufferedReader br = new BufferedReader(new InputStreamReader(stdout));   
                // // copy log file
                // SCPClient client = new SCPClient(this.conn);
                // Session sess = this.conn.openSession();
                //
                // // close connection
                // sess.close();
                // this.conn.close();
                
                // session.close();
                long endTime = System.currentTimeMillis(); // 获取结束时间
                System.out.println("read file is finshed:" + (endTime - startTime) + "ms");// logger.info
                return true;               
            }             
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } 
        
        return false;
    }

    public static void main(String[] args) throws Exception {
//        Exemple2 aa = new Exemple2();
//        aa.copyLogFile("error.log", 0L);
//        // aa.copyLogFile(fileName, 0L);
        
        String path = "/app/jetty/server/SHIVA_OMS_CNSZ22_JETTY_APP_REC_ORDER_01/logs/";
        String fileName = "novatar_20180412.0.log";
        SshTransferHelper ssh1 = new SshTransferHelper("10.202.38.213", "appdeploy", "sf123456");
        
        long startTime = System.currentTimeMillis(); // 获取开始时间
        InputStream is = ssh1.getFileContent(path + fileName);
        long endTime = System.currentTimeMillis(); // 获取结束时间
        System.out.println("get file content is finshed:" + (endTime - startTime) + "ms");
        // SshTransferHelper.readByLine(is);

//        String dest = "E:\\tempFromLinux.tmp";//
//        long startTime1 = System.currentTimeMillis(); // 获取开始时间
//        ssh1.copyFile(path + fileName, "E:\\");
//        InputStream is1 = new FileInputStream(new File(dest));
//        long endTime1 = System.currentTimeMillis(); // 获取结束时间
//        System.out.println("copy file content is finshed:" + (endTime1 - startTime1) + "ms");
//        // SshTransferHelper.readByLine(is1);
        
//        long startTime2 = System.currentTimeMillis(); // 获取开始时间
//        LogViewerParserService service = new LogViewerParserService();
//        // TIMESTAMP LEVEL NDC THREAD LINE CLASS METHOD MESSAGE
//        String pattern = "TIMESTAMP [THREAD] LEVEL CLASS(METHOD) - MESSAGE";
//        service.init("log4j", pattern, "MM-dd HH:mm:ss.SSS", "aa", "UTF-8");
//        Map<String, Integer> categoryNames = new HashMap<>();
//        List<LogData> list = service.regroup(is, categoryNames);
//        System.out.println("共 " + list.size() + "条");
////        list.stream().forEach(data -> System.out.println(createPrintData(data)));
//        long endTime2 = System.currentTimeMillis(); // 获取结束时间
//        System.out.println("parse file content is finshed:" + (endTime2 - startTime2) + "ms");
//
//        long startTime3 = System.currentTimeMillis(); // 获取开始时间
//        File logfile1 = new File("C:\\Users\\la.01367604\\Desktop\\日志\\CX微服务\\error.log.2018-03-12\\error.log.2018-03-12");
//        InputStream in = new FileInputStream(logfile1);
//        String pattern2 = "TIMESTAMP LEVEL NDC THREAD LINE CLASS METHOD MESSAGE";
//        service.init("log4j", pattern2, "yyyy-MM-dd HH:mm:ss", "aa", "UTF-8");
//        Map<String, Integer> categoryNames3 = new HashMap<>();
//        List<LogData> list3 = service.regroup(in, categoryNames3);
//        System.out.println("共 " + list3.size() + "条");
//        list3.stream().forEach(data -> System.out.println(createPrintData(data)));
//        long endTime3 = System.currentTimeMillis(); // 获取结束时间
//        System.out.println("parse local file content is finshed:" + (endTime3 - startTime3) + "ms");
    }

    private static final String printFormat = "LogData-%d：【dataTime】=%s, 【level】=%s, 【thread】=%s, 【ndc】=%s, 【line】=%s, 【loggerName】=%s, 【note】=%s, 【clazz】=%s, 【method】=%s, 【message】=%s";
    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("MM-dd HH:mm:ss");

    private static String createPrintData(LogData data) {
        return String.format(printFormat, data.getId(), dateTimeFormat.format(data.getDate()),
            data.getLevel(), data.getThread(), data.getLine(), data.getClazz(), data.getMethod(),
            data.getMessage());
    }
    public static void ssh1() {
        SshClient client = new SshClient();
        try {
            client.connect("10.202.41.26");
            // 设置用户名和密码
            PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();
            pwd.setUsername("appdeploy");
            pwd.setPassword("sf123456");
            int result = client.authenticate(pwd);
            if (result == AuthenticationProtocolState.COMPLETE) {// 如果连接完成
                System.out.println("===============" + result);
                List<SftpFile> list = client.openSftpClient().ls("/home/appdeploy/appointment/logs/");
                for (SftpFile f : list) {
                    System.out.println(f.getFilename());
                    System.out.println(f.getAbsolutePath());
                    if (f.getFilename().equals("error.log")) {
                        FileOutputStream os = new FileOutputStream("d:/down/" + f.getFilename());
                        client.openSftpClient().get("/home/appdeploy/appointment/logs/error.log", os);
                        // 以行为单位读取文件start
                        File file = new File("d:/mail/aliases");
                        BufferedReader reader = null;
                        try {
                            System.out.println("以行为单位读取文件内容，一次读一整行：");
                            reader = new BufferedReader(new FileReader(file));
                            String tempString = null;
                            int line = 1;// 行号
                            // 一次读入一行，直到读入null为文件结束
                            while ((tempString = reader.readLine()) != null) {
                                // 显示行号
                                System.out.println("line " + line + ": " + tempString);
                                line++;
                            }
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (reader != null) {
                                try {
                                    reader.close();
                                } catch (IOException e1) {
                                }
                            }
                        }
                        // 以行为单位读取文件end
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
